package com.qf.mvc2203.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//有个特殊的接口
public class ProductInterceptor implements HandlerInterceptor {
    /**
     * 注意，返回值 如果为 true，代表当前请求可以继续向后发送给 Controller中的handler方法
     * 如果返回false，那么当前的请求到此为止
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("pre~~~~~~");
        long start = System.currentTimeMillis();//开始时间戳

        request.setAttribute("start",start);//共享时间

        // 判断当前请求是否登录过
        final String token = request.getHeader("token");

        if (token!=null){
            return true;  // 放行当前请求，会让请求继续交给后面的 handler 处理
        }else {
            // 用户没有登录过 ，重定向到 登录页
            response.sendRedirect("/from.html");

            // 要让请求就此打住，不要再给后面的handler发送了
            return  false;

        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("post~~~~~~");
        //获取上面的共享时间
        long start = (long) request.getAttribute("start");
        //结束时间戳
        long end = System.currentTimeMillis();
        //结束时间减去开始时间  就是共执行了多久
        System.out.println(handler+"执行时长："+(end-start));

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion~~~~~~");
    }
}
